import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:io';
import 'dart:ui' as ui show window;
import 'package:lib_uikit/lib_uikit.dart';
import 'package:lib_uikit/resource/resources.dart';

import '../theme/gt_colors_v3.dart';

/// 通用导航栏
class GTAppBarV3 extends StatefulWidget implements PreferredSizeWidget {
  const GTAppBarV3({Key? key,
    this.title,
    this.backIcon,
    this.backPrePressed,
    this.backPressed,
    this.rightIcon1,
    this.rightIcon1Pressed,
    this.rightIcon2,
    this.rightIcon2Pressed,
    this.backgroundColor,
    this.brightness,
    this.shouldReserveStatusBarHeight = true,
    this.overlayStyle,
    this.rightIcon1PressedWithContext,
    this.coinUrl,
    this.titleRightWidget,
    this.mainAxisAlignment,
    this.titleColor,
    this.titleSize,
  })
      : super(key: key);

  final String? title;
  final Widget? backIcon;

  final Color? backgroundColor;

  // 点击返回按钮后，前置操作，不会覆盖默认操作
  final VoidCallback? backPrePressed;

  // 点击返回按钮操作，会覆盖默认操作
  final VoidCallback? backPressed;
  final VoidCallback? rightIcon1Pressed;
  final ValueChanged<BuildContext>? rightIcon1PressedWithContext;

  final Widget? rightIcon1;

  final VoidCallback? rightIcon2Pressed;
  final Widget? rightIcon2;

  // 状态栏主题模式
  final Brightness? brightness;

  // 是否预留状态栏高度
  final bool shouldReserveStatusBarHeight;

  final SystemUiOverlayStyle? overlayStyle;
  final String? coinUrl;
  final Widget? titleRightWidget;
  final MainAxisAlignment? mainAxisAlignment;

  final Color? titleColor;

  final double? titleSize;

  @override
  State<StatefulWidget> createState() => _GTAppBarStateV3();

  @override
  Size get preferredSize {
    if (Platform.isAndroid) {
      return Size(MediaQueryData
          .fromWindow(ui.window)
          .size
          .width, shouldReserveStatusBarHeight ? 44 : 44 - 29);
    } else {
      return Size(MediaQueryData
          .fromWindow(ui.window)
          .size
          .width, 44);
    }
  }
}

class _GTAppBarStateV3 extends State<GTAppBarV3> {
  double _left = 48,
      _right = 48;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: widget.overlayStyle ??
          GTSystemUiOverlayStyleUtils.getStyleForBackgroundColor(
              widget.backgroundColor),
      child: _buildAppBar(context),
    );
  }

  Widget _buildAppBar(BuildContext context) {
    bool isChina = GTThemeProvider.instance.isChina;
    TextStyle textStyle = gtTextStyleW500();
    if (widget.rightIcon1 != null && widget.rightIcon2 != null) {
      _left = 84;
      _right = 84;
    }
    if (widget.mainAxisAlignment == MainAxisAlignment.start) {
      _left = 40;
      textStyle = gtTextStyleW700();
    }
    return Container(
      color: widget.backgroundColor ?? GTColorsV3.bg1.color,
      padding: EdgeInsets.only(
          top: widget.shouldReserveStatusBarHeight ? MediaQuery
              .of(context)
              .padding
              .top : 0),
      constraints: const BoxConstraints.expand(),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Positioned.directional(
            textDirection: Directionality.of(context),
            start: 0,
            //Android机中文环境下，文字上下内边距不一样，看起来文字没有水平居中
            //把箭头往下挪1，达到水平居中的视觉效果
            top: isChina && Platform.isAndroid ? 1 : 0,
            child: GTBackButton(
              backIcon: widget.backIcon,
              onPressed: widget.backPressed ??
                      () {
                    // 先执行前置操作
                    widget.backPrePressed?.call();

                    if (Navigator.of(context).canPop()) {
                      Navigator.of(context).pop();
                    } else {
                      SystemNavigator.pop(animated: true);
                    }
                  },
            ),
          ),
          Container(
            padding: GTEdgeInsetsOnly(left: _left, right: _right),
            child: Row(
              mainAxisAlignment: widget.mainAxisAlignment ??
                  MainAxisAlignment.center,
              children: [
                if ((widget.coinUrl ?? "").isNotEmpty) ...[
                  GTImage(
                    width: 24,
                    height: 24,
                    url: widget.coinUrl,
                    radiusAll: 12,
                    showPlaceholder: true,
                    fit: BoxFit.cover,
                    errorPath: Images.icLendDefaultCoinIcon,
                    placeholderPath: Images.icLendDefaultCoinIcon,
                  ),
                  const SizedBox(width: 8),
                ],
                Flexible(
                  child: Text(
                    widget.title ?? '',
                    softWrap: true,
                    textAlign: TextAlign.center,
                    style: textStyle.copyWith(fontSize: widget.titleSize ?? 18,
                        color: widget.titleColor ?? GTColorsV3.text1.color),
                  ),
                ),
                if (widget.titleRightWidget != null) ...[
                  const SizedBox(
                    width: 4,
                  ),
                  widget.titleRightWidget!
                ]
              ],
            ),
          ),
          Positioned.directional(
            textDirection: Directionality.of(context),
            end: 0,
            child: SizedBox(
              height: 44,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: (widget.rightIcon1 != null ||
                    widget.rightIcon2 != null)
                    ? [
                  if (widget.rightIcon2 != null)
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: widget.rightIcon2Pressed,
                      child: widget.rightIcon2,
                    ),
                  if (widget.rightIcon1 != null &&
                      widget.rightIcon2 != null) const SizedBox(width: 16),
                  if (widget.rightIcon1 != null) ...[
                    if (widget.rightIcon1PressedWithContext != null) ...[
                      Builder(
                        builder: (BuildContext context) {
                          return GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () {
                              if (widget.rightIcon1PressedWithContext != null) {
                                widget.rightIcon1PressedWithContext!(context);
                              }
                            },
                            child: widget.rightIcon1!,
                          );
                        },
                      ),
                    ] else
                      ...[
                        GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: widget.rightIcon1Pressed,
                          child: widget.rightIcon1,
                        )
                      ]
                  ]
                ]
                    : [const SizedBox.shrink()],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
